<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref, watch } from 'vue'

// 统计信息类型
interface PlaceholderStatistics {
  total_placeholders: number
  active_placeholders: number
  today_generated: number
  by_service_type: Record<string, number>
  by_office_code: Record<string, number>
}

// 批量生成结果类型
interface GenerateBatchResult {
  success: boolean
  total_count: number
  success_count: number
  failed_count: number
  generated_ids: number[]
  errors: Array<{ index: number, message: string }>
}

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
  (e: 'generatingChange', generating: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 数据状态
const loading = ref(false)
const generating = ref(false)
const statistics = ref<PlaceholderStatistics>({
  total_placeholders: 0,
  active_placeholders: 0,
  today_generated: 0,
  by_service_type: {},
  by_office_code: {},
})
const lastGenerateResult = ref<GenerateBatchResult | null>(null)

// 生成表单
const generateForm = reactive({
  count: 10,
  issuing_country: 'CN',
  issuing_authority: 'GD',
  service_type: 'DI',
  office_code: 'HKLO',
  priority: 1,
  email_mode: 'random' as 'random' | '2925' | 'fixed',
  fixed_email: 'zhzr516688@2925.com',
})

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: value => emit('update:modelValue', value),
})

const authorityOptions = computed(() => {
  if (generateForm.issuing_country === 'CN') {
    return [
      { label: '广东省', value: 'GD' },
      { label: '其他省市', value: 'OTH' },
    ]
  }
  else {
    return [
      { label: '其他', value: 'OTH' },
    ]
  }
})

// 加载数据
async function loadData() {
  loading.value = true
  try {
    const response = await window.api.placeholder.statistics()
    if (response.success) {
      statistics.value = response.data
    }
    else {
      ElMessage.error(response.error || '加载统计信息失败')
    }
  }
  catch (error) {
    console.error('加载占号数据统计失败:', error)
    ElMessage.error('加载统计信息失败')
  }
  finally {
    loading.value = false
  }
}

// 生成占号数据
async function generatePlaceholders() {
  if (!generateForm.count || generateForm.count <= 0) {
    ElMessage.warning('请输入有效的生成数量')
    return
  }

  generating.value = true
  emit('generatingChange', true)
  try {
    const response = await window.api.placeholder.generateBatch({
      count: generateForm.count,
      issuing_country: generateForm.issuing_country,
      issuing_authority: generateForm.issuing_authority,
      service_type: generateForm.service_type,
      office_code: generateForm.office_code,
      priority: generateForm.priority,
      remarks: '批量生成的占号数据',
      concurrent_limit: 5,
      email_mode: generateForm.email_mode === 'fixed'
        ? { fixed: generateForm.fixed_email }
        : (generateForm.email_mode === '2925' ? { use2925: true } : undefined),
    })

    if (response.success) {
      lastGenerateResult.value = response.data

      if (response.data.success) {
        ElMessage.success(`生成成功！共生成 ${response.data.success_count} 个占号数据`)
      }
      else {
        ElMessage.warning(`生成部分成功：成功 ${response.data.success_count}，失败 ${response.data.failed_count}`)
      }

      // 刷新统计信息
      await loadData()
      emit('success')
    }
    else {
      ElMessage.error(response.error || '生成占号数据失败')
    }
  }
  catch (error) {
    console.error('生成占号数据失败:', error)
    ElMessage.error('生成占号数据失败')
  }
  finally {
    generating.value = false
    emit('generatingChange', false)
  }
}

// 重置生成表单
function resetGenerateForm() {
  Object.assign(generateForm, {
    count: 10,
    issuing_country: 'CN',
    issuing_authority: 'GD',
    service_type: 'DI',
    office_code: 'HKLO',
    priority: 1,
  })
  lastGenerateResult.value = null
}

// 监听签发国家变化
function watchIssuingCountry() {
  if (generateForm.issuing_country === 'OTH') {
    generateForm.issuing_authority = 'OTH'
  }
  else {
    generateForm.issuing_authority = 'GD'
  }
}

// 监听签发国家变化
watch(() => generateForm.issuing_country, watchIssuingCountry)
</script>

<template>
  <el-dialog
    v-model="visible"
    title="占号数据管理"
    width="900px"
    @open="loadData"
  >
    <div class="placeholder-management">
      <!-- 统计信息 -->
      <div class="stats-section">
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-number">
              {{ statistics.total_placeholders || 0 }}
            </div>
            <div class="stat-label">
              总占号数
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-number">
              {{ statistics.active_placeholders || 0 }}
            </div>
            <div class="stat-label">
              活跃占号
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-number">
              {{ statistics.today_generated || 0 }}
            </div>
            <div class="stat-label">
              今日生成
            </div>
          </div>
        </div>
      </div>

      <!-- 操作区域 -->
      <div class="actions-section">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>批量生成占号数据</span>
            </div>
          </template>

          <el-form :model="generateForm" label-width="120px" inline>
            <el-form-item label="生成数量">
              <el-input-number
                v-model="generateForm.count"
                :min="1"
                :max="1000"
                placeholder="数量"
                style="width: 120px"
              />
            </el-form-item>

            <el-form-item label="签发国家">
              <el-select v-model="generateForm.issuing_country" style="width: 120px">
                <el-option label="中国内地" value="CN" />
                <el-option label="海外" value="OTH" />
              </el-select>
            </el-form-item>

            <el-form-item label="签发机关">
              <el-select v-model="generateForm.issuing_authority" style="width: 120px">
                <el-option
                  v-for="option in authorityOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="服务类型">
              <el-select v-model="generateForm.service_type" style="width: 120px">
                <el-option label="DI" value="DI" />
                <el-option label="其他" value="OTHER" />
              </el-select>
            </el-form-item>

            <el-form-item label="办理地点">
              <el-select v-model="generateForm.office_code" style="width: 120px">
                <el-option label="HKLO" value="HKLO" />
                <el-option label="KLO" value="KLO" />
                <el-option label="KTO" value="KTO" />
                <el-option label="STO" value="STO" />
                <el-option label="YLO" value="YLO" />
              </el-select>
            </el-form-item>

            <el-form-item label="优先级">
              <el-select v-model="generateForm.priority" style="width: 100px">
                <el-option label="1级" :value="1" />
                <el-option label="2级" :value="2" />
                <el-option label="3级" :value="3" />
                <el-option label="4级" :value="4" />
                <el-option label="5级" :value="5" />
              </el-select>
            </el-form-item>

            <el-form-item label="邮箱模式">
              <el-select v-model="generateForm.email_mode" style="width: 140px">
                <el-option label="随机邮箱" value="random" />
                <el-option label="2925子邮箱" value="2925" />
                <el-option label="指定邮箱" value="fixed" />
              </el-select>
            </el-form-item>

            <el-form-item v-if="generateForm.email_mode === 'fixed'" label="指定邮箱">
              <el-input v-model="generateForm.fixed_email" style="width: 240px" placeholder="如: zhzr516688@2925.com" />
            </el-form-item>
          </el-form>

          <template #footer>
            <el-button
              type="primary"
              :loading="generating"
              :disabled="!generateForm.count || generateForm.count <= 0"
              @click="generatePlaceholders"
            >
              <el-icon><Plus /></el-icon>
              开始生成
            </el-button>

            <el-button @click="resetGenerateForm">
              重置
            </el-button>
          </template>
        </el-card>
      </div>

      <!-- 动态生成规则提示 -->
      <el-alert
        type="info"
        :closable="false"
        show-icon
        class="mb-3"
        :title="`生成规则：身份证按 ${generateForm.issuing_authority === 'GD' ? '广东省' : '其他省份'} GB11643-1999 生成；证件号为 C/E 前缀(1-2位)+数字(共9位)；邮箱模式：${generateForm.email_mode === 'fixed' ? `指定 ${generateForm.fixed_email}` : (generateForm.email_mode === '2925' ? 'zhzr516688随机@2925.com' : '更真实的随机域名邮箱')}`"
      />

      <!-- 生成结果 -->
      <div v-if="lastGenerateResult" class="result-section">
        <el-alert
          :title="`生成完成：成功 ${lastGenerateResult.success_count} 个，失败 ${lastGenerateResult.failed_count} 个`"
          :type="lastGenerateResult.success ? 'success' : 'warning'"
          :closable="false"
          show-icon
        />

        <div v-if="lastGenerateResult.errors && lastGenerateResult.errors.length > 0" class="error-details">
          <h4>错误详情：</h4>
          <ul>
            <li v-for="error in lastGenerateResult.errors.slice(0, 5)" :key="error.index">
              第 {{ error.index + 1 }} 个：{{ error.message }}
            </li>
            <li v-if="lastGenerateResult.errors.length > 5">
              还有 {{ lastGenerateResult.errors.length - 5 }} 个错误...
            </li>
          </ul>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="loadData">
          刷新统计
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.placeholder-management {
  padding: 16px 0;
}

.stats-section {
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.actions-section {
  margin-bottom: 24px;
}

.card-header {
  font-weight: 600;
}

.generate-actions {
  margin-top: 16px;
  display: flex;
  gap: 8px;
}

.result-section {
  margin-bottom: 24px;
}

.error-details {
  margin-top: 12px;
  padding: 12px;
  background: #fdf6ec;
  border-radius: 4px;
}

.error-details h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #e6a23c;
}

.error-details ul {
  margin: 0;
  padding-left: 20px;
}

.error-details li {
  font-size: 12px;
  color: #e6a23c;
  margin-bottom: 4px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item) {
  margin-bottom: 12px;
}

:deep(.el-form-item__label) {
  font-size: 13px;
}
</style>
